package cn.k7g.codeflow.service;

import cn.k7g.codeflow.annotation.NodeFlag;
import cn.k7g.codeflow.model.node.CodeNode;
import cn.k7g.codeflow.model.node.CodeNodeClass;
import cn.k7g.codeflow.model.node.impl.MethodNode;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
@Slf4j
public class CodeNodeService {

    private ListableBeanFactory beanFactory;

    public List<CodeNode> listCodeNode() {
        Map<String, CodeNodeClass> beansOfType = beanFactory.getBeansOfType(CodeNodeClass.class);

        List<CodeNode> ret = new ArrayList<>();
        beansOfType.forEach((k, v) -> {
            for (Method method : v.getClass().getMethods()) {
                NodeFlag annotation = method.getAnnotation(NodeFlag.class);
                if (annotation == null) {
                    continue;
                }
                MethodNode methodNode = new MethodNode(method);
                ret.add(methodNode);
                log.info("已经加载函数节点：{} @ {}", k, method.getName());
            }
        });
        return ret;
    }
}
